package com.shangxian.giveithome.service.impl;


import com.shangxian.giveithome.code.CommonCode;
import com.shangxian.giveithome.code.PetCode;
import com.shangxian.giveithome.controller.ImgFeiServer;
import com.shangxian.giveithome.controller.MechanismServer;
import com.shangxian.giveithome.entity.Asylum;
import com.shangxian.giveithome.entity.AsylumCreate;
import com.shangxian.giveithome.entity.AsylumDetails;
import com.shangxian.giveithome.entity.AsylumInfo;
import com.shangxian.giveithome.entity.AsylumScreen;
import com.shangxian.giveithome.entity.AsylumStatus;
import com.shangxian.giveithome.entity.AsylumUpdate;
import com.shangxian.giveithome.entity.Img;
import com.shangxian.giveithome.entity.Mechanism;
import com.shangxian.giveithome.entity.PageableDetails;
import com.shangxian.giveithome.entity.Pet;
import com.shangxian.giveithome.entity.PetCreate;
import com.shangxian.giveithome.entity.Place;
import com.shangxian.giveithome.exception.ExceptionUtils;
import com.shangxian.giveithome.mapper.AdoptionMapper;
import com.shangxian.giveithome.mapper.AsylumMapper;
import com.shangxian.giveithome.mapper.PetMapper;
import com.shangxian.giveithome.mapper.PlaceMapper;
import com.shangxian.giveithome.result.Result;
import com.shangxian.giveithome.service.AsylumService;
import com.shangxian.giveithome.utils.IGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

import static com.shangxian.giveithome.entity.MechanismDataUp.AsylumNumber;
import static com.shangxian.giveithome.utils.DateTime.YMD;
import static com.shangxian.giveithome.utils.DateTime.getTime;


@Service
public class AsylumServiceImpl implements AsylumService {


  @Resource
  private AdoptionMapper adoptionMapper;

  @Resource
  private AsylumMapper asylumMapper;

  @Resource
  private ImgFeiServer imgFeiService;


  @Autowired
  private IGenerator iGenerator;

  @Resource
  private MechanismServer mechanismServer;

  @Resource
  private PetMapper petMapper;

  @Resource
  private PlaceMapper placeMapper;

  /**
   * 根据机构id查询收容记录列表
   * 条件等
   *
   * @param asylumScreen
   * @param pageNum
   * @param pageSize
   * @return
   */
  @Override
  public PageableDetails queryByMechId(AsylumScreen asylumScreen, Integer pageNum, Integer pageSize) {
    List<Asylum> asylums = asylumMapper.queryAsylumMeId(asylumScreen);
    if (CollectionUtils.isEmpty(asylums)) {
      return null;
    }

    List<Long> petIdS = asylums.stream().map(Asylum::getPetId).collect(Collectors.toList());
    Integer counts = petMapper.queryCountAsylum(petIdS, asylumScreen);
    if (counts == 0) {
      return null;
    }
    List<Pet> pets = petMapper.queryByAsylum(petIdS, asylumScreen, pageNum * pageSize, pageSize);
    if (CollectionUtils.isEmpty(pets)) {
      return null;
    }
    //总条数
    int totalPages = 0;
    if (counts % pageSize != 0) {
      totalPages += 1;
    }
    //收集收容id集合
    List<Long> imgId = asylums.stream().map(Asylum::getImgId).collect(Collectors.toList());
    //查询图片
    List<Img> imgs = imgFeiService.queryImagesByIds(imgId);
    if (CollectionUtils.isEmpty(imgs)) {
      ExceptionUtils.error(CommonCode.DATA_ERRORS);
    }
    List<AsylumInfo> convert = iGenerator.convert(pets, AsylumInfo.class);
    //判断图片集合是否为空
    //将查询的数据添加到集合中
    convert.forEach(asylum -> {
      asylums.forEach(asylum1 -> {
        if (asylum1.getPetId().equals(asylum.getId())) {
          imgs.forEach(img -> {
            if (img.getKeyId().equals(asylum1.getImgId())) {
              asylum.setPath(img.getPath());
            }
          });
        }
      });
    });

    return new PageableDetails<>(pageNum, pageSize, counts, totalPages, convert);

  }

  /**
   * 创建机构收容
   *
   * @param asylumCreate
   */
  @Override
  @Transactional
  public void create(AsylumCreate asylumCreate) {
    asylumCreate.setCreateTime(getTime(YMD));
    asylumCreate.setSubordinate(3);
    PetCreate petCreate = iGenerator.convert(asylumCreate, PetCreate.class);
    petMapper.save(petCreate);
    asylumMapper.save(asylumCreate, petCreate.getId());
    mechanismServer.updateMechanismData(
            AsylumNumber(asylumCreate.getMeId(), true, true));

  }

  /**
   * 修改机构收容
   *
   * @param asylumUpdate
   */
  @Override
  @Transactional
  public void update(AsylumUpdate asylumUpdate) {
    Integer existence = asylumMapper.queryExistence(asylumUpdate.getId());
    if (existence == 0) {
      ExceptionUtils.error(CommonCode.DATA_ERRORS);
    }
    asylumUpdate.setSubordinate(3);
    asylumUpdate.setCreateTime(getTime(YMD));
    PetCreate petCreate = iGenerator.convert(asylumUpdate, PetCreate.class);
    asylumMapper.update(asylumUpdate);
    petMapper.update(petCreate);

  }

  /**
   * 删除收容记录
   *
   * @param id
   * @param aLong
   */
  @Override
  @Transactional
  public void delete(Long id, Long aLong) {
    Asylum asylum = asylumMapper.queryExistences(id);
    if (asylum == null) {
      ExceptionUtils.error(CommonCode.DATA_ERRORS);
    }
    if (!asylum.getMeId().equals(aLong)) {
      ExceptionUtils.error(PetCode.NOT_AUTH_DEL_DATA);
    }
    asylumMapper.delete(id);
    Integer count = 0;
    //判断是否已领养状态
    if (asylum.getStatus().equals(3L)) {
      //若是已领养则判断是否线上被领养
      count = adoptionMapper.queryByPlaceSu(id);
    }
    //若不是线上被领养则删除其他相关数据
    if (count == 0) {
      petMapper.delete(id);
      mechanismServer.updateMechanismData(
              AsylumNumber(aLong, true, false));
      if (asylum.getStatus().equals(2L)) {
        placeMapper.delete(aLong, id);
      }
      Result result = imgFeiService.deleteKeyId(aLong, asylum.getImgId());
      if (!result.getCode().equals(200)) {
        ExceptionUtils.error(CommonCode.DATA_ERRORS);
      }
    }
  }

  /**
   * 修改收容状态
   *
   * @param asylumStatus
   */
  @Override
  @Transactional
  public void updateStatus(AsylumStatus asylumStatus) {
    Asylum asylum = asylumMapper.queryByAsylumStatus(asylumStatus.getId());
    if (!asylum.getMeId().equals(asylumStatus.getALong())) {
      ExceptionUtils.error(CommonCode.DATA_ERRORS);
    }
    Long statust = asylum.getStatus();
    Long status = asylumStatus.getStatus();
    if (statust == 0L) {
      ExceptionUtils.error(PetCode.ASYLUM_DEL_ERROR);
    }
    //当前是收容中的处理
    if (statust == 1L) {
      if (status == 1L) {
        ExceptionUtils.error(PetCode.ASYLUM_1_ERROR);
      }
      if (status == 2L) {
        upStatus2(asylum, asylumStatus);
      }
    }
    //当前是待领养的处理
    if (statust == 2L) {
      if (status == 2L) {
        ExceptionUtils.error(PetCode.ASYLUM_2_ERROR);
      }
      if (status == 3L || status == 0L || status == 1L) {
        Integer exience = placeMapper.queryByAsylum(asylumStatus.getALong(), asylumStatus.getId());
        if (exience > 0) {
          placeMapper.delete(asylumStatus.getALong(), asylumStatus.getId());
          petMapper.updateSubordinate(asylum.getPetId(), 3);
        }
      }
    }
    //当前是已领养的处理
    if (statust == 3L) {
      if (status == 2L) {
        Integer count = adoptionMapper.queryByPlaceSu(asylumStatus.getId());
        if (count == 0) {
          upStatus2(asylum, asylumStatus);
        } else {
          ExceptionUtils.error(PetCode.ASYLUM_ADOPTION_ERROR);
        }
      }
      if (status == 3L) {
        ExceptionUtils.error(PetCode.ASYLUM_3_ERROR);
      }
      if (status == 1 || status == 0) {
        ExceptionUtils.error(PetCode.ASYLUM_ADOPTION_ERROR);
      }
    }
    asylumMapper.updateAsylumStatus(asylumStatus.getId(), status);
  }

  @Transactional
  public void upStatus2(Asylum asylum, AsylumStatus asylumStatus) {
    Mechanism mechanism = mechanismServer.queryByMechanismAsylum(asylumStatus.getALong());
    Place place = iGenerator.convert(asylum, Place.class);
    place.setPhone(mechanism.getPhone());
    place.setWechat(mechanism.getWechat());
    place.setCondition("领养条件,请向该机构咨询");
    place.setCreateTime(getTime(YMD));
    placeMapper.saveAsylum(place);
    petMapper.updateSubordinate(asylum.getPetId(), 4);
  }


  /**
   * 查询收容详情信息
   *
   * @param id
   * @return
   */
  @Override
  public AsylumDetails queryByAsylumDetails(Long id) {
    Pet pet = petMapper.queryByAsylumDetails(id);
    if (pet == null) {
      ExceptionUtils.error(CommonCode.DATA_ERROR);
    }
    Asylum asylum = asylumMapper.queryByAsylumDetails(pet.getId());
    AsylumDetails asylumDetails = iGenerator.convert(pet, AsylumDetails.class);
    asylumDetails.setRescuerWechat(asylum.getRescuerWechat());
    asylumDetails.setRescuerImg(asylum.getRescuerImg());
    asylumDetails.setRescuerPhone(asylum.getRescuerPhone());
    asylumDetails.setStatus(asylum.getStatus());
    asylumDetails.setImgs(imgFeiService.queryImagesByImgs(asylum.getImgId()));
    return asylumDetails;
  }

}
